
#--------------------------------
#
# API FUNCTIONS
#
#--------------------------------

import LocsiCFG
import datetime
import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

#
# AUTHENTICATE
#

def authenticategooglecalendarapi():
    
    FLAGS = gflags.FLAGS

    # Set up a Flow object to be used if we need to authenticate. This
    # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
    # the information it needs to authenticate. Note that it is called
    # the Web Server Flow, but it can also handle the flow for native
    # applications
    # The client_id and client_secret are copied from the API Access tab on
    # the Google APIs Console
    FLOW = OAuth2WebServerFlow(
        client_id=LocsiCFG.client_id,
        client_secret=LocsiCFG.client_secret,
        scope=LocsiCFG.scope,
        user_agent=LocsiCFG.user_agent)
    
    # To disable the local server feature, uncomment the following line:
    FLAGS.auth_local_webserver = False

    # If the Credentials don't exist or are invalid, run through the native client
    # flow. The Storage object will ensure that if successful the good
    # Credentials will get written back to a file.
    storage = Storage('calendar.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid == True:
      credentials = run(FLOW, storage)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Build a service object for interacting with the API. Visit
    # the Google APIs Console
    # to get a developerKey for your own application.
    service = build(serviceName='calendar', version='v3', http=http,
           developerKey=LocsiCFG.developerKey)

    return service

# Get list of calnedars sample code
"""
page_token = None
while True:
  calendar_list = service.calendarList().list(pageToken=page_token).execute()
  if calendar_list['items']:
    for calendar_list_entry in calendar_list['items']:
      print calendar_list_entry['summary']
  page_token = calendar_list.get('nextPageToken')
  if not page_token:
    break
"""

def geteventfromcalendar(service, eventId):
    event = []

    event = service.events().get(calendarId='primary', eventId = eventId).execute()

    return event

def updateeventincalendar(service, eventToUpdate):
    event = []

    #print eventToUpdate['id']

    event = service.events().update(calendarId='primary', eventId=eventToUpdate['id'], body=eventToUpdate).execute()

    return event

def geteventsfromcalendar(service, fromCalendar):
    allEvents = []

    page_token = None

    while True:
        events = service.events().list(calendarId=fromCalendar, pageToken=page_token).execute()
        #print events

        if events['items']:
          allEvents.extend(events['items'])
          #for event in events['items']:
          #   print event

        page_token = events.get('nextPageToken')

        if not page_token:
            break

    return allEvents


def geteventsfromcalendarintimewindow(service, fromCalendar, hoursm = 4, hoursp= 168):
    allEvents = []

    dt = datetime.datetime.utcnow()
    
    # beginning and end = now +/- 12 hours
    dt_begin=dt - datetime.timedelta(hours=hoursm)
    dt_last=dt + datetime.timedelta(hours=hoursp)

    # this is the time slot we want to look at
    begin  = dt_begin.isoformat()[:19] + 'Z'
    last = dt_last.isoformat()[:19] + 'Z'
    #begin  = dt_begin.isoformat()[:19]
    #last = dt_last.isoformat()[:19]
    
    #change this if you want to access a different calendar
    calID='primary'

    page_token = None
    # print "Ordered"
    events = service.events().list(calendarId=calID, orderBy="startTime", singleEvents=True, timeMin=begin, timeMax=last ).execute()
    
    # just a test to see if there is anything there,
    # returns None if there are no events to display
    eventTest = events.get( 'items', None)

    while eventTest != None :
        allEvents.extend(events['items'])
        #print events['items']
        
        for event in events['items']:
            

            # print event['start']
            # print type(event)

            orgPerson = str(event['organizer']).split('\'')[3]
            eventStart = str(event['start']).split('\'')[3]
            eventEnd = str(event['end']).split('\'')[3]

            dt_eventStart = datetime.datetime.strptime(eventStart[:-6],"%Y-%m-%dT%H:%M:%S")
            dt_eventEnd = datetime.datetime.strptime(eventEnd[:-6],"%Y-%m-%dT%H:%M:%S")
            dt_duration = dt_eventEnd - dt_eventStart

            #print 'Duration:',dt_duration
            
            #print datetime.datetime.strptime(eventStart[:-6],"%Y-%m-%dT%H:%M:%S"), eventEnd, orgPerson
        
        page_token = events.get('nextPageToken')
        if not page_token:
            break
        
    return allEvents
